<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;

class AdminController extends Controller
{
	public function beforeAction($action)
	{
		if($action->id == "index" || $action->id == "logout")
		{
			if(!(isset($_SESSION['cms_userid']) && $_SESSION['cms_userid'] != null && $_SESSION['cms_usertype'] != 1))
			{
				return $this->redirect(['login']);
			}
			// if ($_SESSION['usertype'] == 1) {
			// 	throw new NotFoundHttpException("没有权限");
			
			// }
		}

		if($action->id == "login" || $action->id == "dologin")
		{
			if(isset($_SESSION['cms_userid']) && $_SESSION['cms_userid'] != null)
			{
				return $this->redirect(['index']);
			}
		}
		
		return true;
	}

	public function actionIndex()
	{
		return $this->render("index");
	}

	public function actionLogin()
	{
		$msg = '';
		if (isset($_GET['msg'])) {
			$msg = $_GET['msg'];
		}
		return $this->render("login",['msg'=>$msg]);
	}

	public function actionDologin()
	{
		$username = $_POST['username'];
		$connection = Yii::$app->db;
		$user = $connection->createCommand("SELECT * FROM tbl_user WHERE username='$username'")->queryOne();
		
		if($user && strtolower($user['password']) == strtolower(md5($_POST['password'])) && $user['usertype'] != 1)
		{
			$_SESSION['cms_userid'] = $user['id'];
			$_SESSION['cms_truename'] = $user['truename'];
			$_SESSION['cms_usertype'] = $user['usertype'];
			$_SESSION['cms_username'] = $user['username'];

			return $this->redirect(['index']);
		}
		else
		{
			return $this->redirect(['login','msg'=>'用户名或密码错误']);
		}
	}

	public function actionLogout()
	{
		unset($_SESSION['cms_userid']);
		//var_dump($_SESSION);die();
		return $this->redirect(['login']);
	}

	public function actionTest()
	{
		//session_start();
		var_dump($_SESSION);
	}
}